package com.suning.sawp.service.impl.esb;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import com.suning.rsc.RscException;
import com.suning.rsc.dto.responsedto.MbfResponse;
import com.suning.rsc.httpservice.annotation.EsbEIHttpWired;
import com.suning.sawp.constants.LoggerConstants;
import com.suning.sawp.dto.esb.QryPromExecDetailReq;
import com.suning.sawp.dto.esb.QryPromExecDetailRsp;
import com.suning.sawp.intf.esb.PromotionSysService;
import com.suning.sawp.intf.esb.PromotionaMgmtService;
import com.suning.sawp.service.util.XmlUtils;

/**
 * 
 * 〈一句话功能简述〉<br> 
 * 〈功能详细描述〉
 *
 * @author 13082136
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Service
public class PromotionaMgmtServiceImpl implements PromotionaMgmtService {
    
    private PromotionSysService promotionSysService;
    
    private static final Logger LOGGER = LoggerFactory.getLogger(LoggerConstants.SAWP_INTEGRATION);

    private static final String SELF = "1";
    
    private static final String PALTFORM = "3";
    
    @Override
    public QryPromExecDetailRsp queryPromotionExecDetail(QryPromExecDetailReq req) throws RscException {
        // 临时解决方案，待促销中心接口调整完成后接入新接口
        // 做两次查询；先查询1，如果没有结果在查询3
        req.setActivitySource(SELF);
        QryPromExecDetailRsp detailRsp = getPromotionExecDetail(req);
        if (null == detailRsp || "0".equals(detailRsp.getQueryResults())) {
            // 自营1未查询到(包括调用失败，查询券失败queryResults节点为0)，查询平台3
            req.setActivitySource(PALTFORM);
            detailRsp = getPromotionExecDetail(req);
        }
        
        return detailRsp;
    }

    private QryPromExecDetailRsp getPromotionExecDetail(QryPromExecDetailReq req) throws RscException {
        QryPromExecDetailRsp output = null;
        MbfResponse mbfResponse = promotionSysService.queryPromotionExecDetail(req);
        
        String xmlData = mbfResponse.getOutput().getMbfBodyXml();
        if(StringUtils.isNotBlank(xmlData)){
            StringBuilder tmp = new StringBuilder();
            tmp.append("<data>").append(xmlData).append("</data>");
            xmlData = tmp.toString();
            Document doc;
            try{
                doc = XmlUtils.getW3CDom(xmlData);
                output = new  QryPromExecDetailRsp();
                output.setQueryResults(XmlUtils.getValueByXpath(doc, "/data/queryResults"));
                output.setFailureReasons(XmlUtils.getValueByXpath(doc, "/data/failureReasons"));
                String isDayRemainLimit = XmlUtils.getValueByXpath(doc, "/data/isDayActRemainLimited");
                String isActRemainLimit = XmlUtils.getValueByXpath(doc, "/data/isActRemainLimited");
                output.setDayActRemainCount(XmlUtils.getValueByXpath(doc, "/data/dayActRemainCount"));//券当天可发剩余库存量
                if("0".equals(isDayRemainLimit) && "0".equals(output.getDayActRemainCount())){
                    output.setDayActRemainCount("-1");
                }
                output.setActRemainCount(XmlUtils.getValueByXpath(doc, "/data/actRemainCount"));//券剩余总库存量
                if("0".equals(isActRemainLimit) && "0".equals(output.getActRemainCount())){
                    output.setActRemainCount("-1");
                }
                return output;
            }catch(Exception e){
                LOGGER.error("现金充值调用POS接口解析报文异常:" + e);
            }
        }
       
        return output;
    }
    
    public PromotionSysService getPromotionSysService() {
        return promotionSysService;
    }

    @EsbEIHttpWired
    public void setPromotionSysService(PromotionSysService promotionSysService) {
        this.promotionSysService = promotionSysService;
    }
    
}
